<?php

  /**
   * 计费类
   */
class Jifei{
   private $ip;
   private $yumi_url;
   public  $lanjiinfo; //拦截信息
   private $uid;       //会员ID
   private $is_phome;  //是否手机访问\
   private $useragent; //用户信息浏览器 操作系统 手机平台
   private $cid;       //分类ID
   private $user_pid;  //会员上级id
   private $user;      //会员所有信息
   private $id;        //文章ID
   private $yzurl;
   //构造方法
   public  function __construct($data){
        $this->ip =  get_ip(); //全局获取到的客户端IP
        $this->uid= (int) de_crypt($data['uid']);
        $this->id= (int) $data['id'];
        $this->is_phome = is_phome();
        $this->yzurl=$data["HTTP_REFERER"];
        //调用UserAgent类
        import("Lib.Useragent.Useragent");
        $Useragent = new \UserAgentFactory();
        $this->useragent=$Useragent->analyze($_SERVER['HTTP_USER_AGENT']);
    }


    //执行入口
    public function run()
    {
      /** if(!C("JIFEI_DEBUG")){
         if(!$this->Simple()){
            return false;
         }
       } **/
       $ip= iplong($this->ip);
       //判断是否是黑名单IP
       if($this->block_ip($ip)){
          return false;
       }
       //匹配是否有这个会员******
       if(!$this->user_uid()){
          return false;
       }
    if(C("JIFEI_DEBUG")){
         if(cookie("k")){
            echo "已经计费或者扣量,不在重新检查!!";
         }
       }
       if(!cookie("k")){
         $this->jifei();
       }
       $this->jifei();
    }



    //计费日志
    private function jifei()
    {
		//过滤微信以外
		//if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
		//	return true;
		//}
        $ip=iplong($this->ip);
        $news_id = $this->id;
        $time= (int)C("JIFEI_LOG_TIME");
        $price = $this->user_dianji();
        $time = time()-$time*3600;
        $M=M("jifeiip_log");
        //查询是否已经计费
       if($M->field("id")->where("ip=".$ip." and time >".$time)->find()){
          if(C("JIFEI_DEBUG")){
             echo "已经计费";
             }
            return false;
        }
         //查询是否已经扣量
        if(M('kouliangip_log')->field("id")->where("ip=".$ip." and time >".$time)->find()){
            if(C("JIFEI_DEBUG")){
            echo "已经扣量";
            }
            return false;
        }
   
        //访客信息
        $data=array(
                 'ip'=>$ip,
                 'time'=>time(),
                 'uid'=>$this->uid,
                 'platform'=>$this->useragent->platform['title'],
                 'browser'=>$this->useragent->browser['title'],
                 'os'=>$this->useragent->os['title'],
                 'useragent'=>$this->useragent->useragent,
                 "url"=>$this->yzurl,
                 "news_id"=>$news_id,
                 "price"=>$price
            );

            //扣量
        if($this->kouliang($data)){
            if(C("JIFEI_DEBUG")){
               echo "扣量";
            }
            return false;
        }
            //加款日志
        $jiakuan_data=array(
                 "uid"=>$this->uid,
                 'time'=>time(),
                 'price'=>$price,
                 'type'=> 1,
                 'info' =>'直接推广加款.',
            );
           //加款以及上级加款事务处理
        $M->startTrans();//在第一个模型里启用就可以了，或者第二个也行
        $add_lanjie=$M->add($data);
        //这里把刚才被拦截的记录给删掉
        $add_user_price = M("user")->lock('true')->where("id=".$this->uid)->setInc("balance",$price); //于额表加款
        $this->time_jifei_ip("ip",1);     // IP加1
        $this->time_jifei_ip("price",$price);  //直接推广加上本次推广金额
        $jiakuan_data['jifei_log_id']=$add_lanjie;
        //是否开启加款日志
        if(C("JIAKUAN_LOG")){
            $add_jiakuan_log = M("jiakuan_log")->add($jiakuan_data); //添加直接推广日志,
        }
        $this->user_shangji_jiakuan($price,$add_lanjie,$add_jiakuan_log); //查询上级和加款
        if($add_lanjie && $add_user_price){
             $M->commit();//成功则提交
             $news_id=$this->id;
             M("news")->where("id=".$news_id)->setInc('pv'); //pv加1
             cookie("k",1);
             return true;
        }else{
             $M->rollback();//不成功，则回滚
             YZLOG("加款事务处理不成功!查看往上日志");
             return false;
        }

    }




    //扣量设置
    private function kouliang($data)
    {
        $user= $this->user;
        if(C("KOULIANG_USER"))
        {
           //读取会员独立扣量配置
           $kouliang_time=$user['kouliang_time'] ? $user['kouliang_time'] : C("KOULIANG_TIME");
           C("KOULIANG_TIME",$kouliang_time);
           $kouliang_bili = $user['kouliang_bili'] ? $user['kouliang_bili']:C("KOULIANG_BILI");
           C("KOULIANG_BILI",$kouliang_bili);
        }
        $kouling_time = C("KOULIANG_TIME")=='0' ? 0 : explode(',',C("KOULIANG_TIME"));
        $kouliang_bili= C("KOULIANG_BILI");
        $kouliang_user_reg_time=C("KOULIANG_USER_REG_TIME");
        $kouliang_user_money_total = C("KOULIANG_USER_MONEY_TOTAL");
        if($kouling_time!==0){
            $time = in_array(date("H"),$kouling_time); // 判断当前时间是否在扣量范围
        }else{
            $time=true; //如果为0则为全时间扣量
        }
        $kouliang_user_reg_time = time() - ((24*3600)*$kouliang_user_reg_time);   //得到配置的时间前的时间戳
        $kouliang_user_reg_time=$user['reg_time'] > $kouliang_user_reg_time ? 0:1;  //如果配置的时间戳大于注册的时间戳不计费
        $kouliang_user_money_total = ($user['balance'] + $user['paid']) >= $kouliang_user_money_total ? 1:0;
        if($kouliang_bili && $time && $kouliang_user_reg_time && $kouliang_user_money_total){
           //条件为真开始扣量 //读取配置
           $bukou= (100-$kouliang_bili)-0.3;
           $kou= $kouliang_bili+0.1;
           $is_kouliang= array(
              0=>$bukou ,//不扣量
              1=>$kou,//扣量
            );
           $is_kouliang= $this->get_rand($is_kouliang);
        }
        if($is_kouliang){
          M("kouliangip_log")->add($data);
          $this->time_jifei_ip('kouliang',1); //扣量加1
          cookie("k",1);
          //记录到扣量日志里面
          return true;
        }else{
          return false;
        }
    }




    //概率计算 10万次计算 相差+-300
    private function get_rand($proArr) {
    $result = '';
    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset ($proArr);

    return $result;
    }



    /**
    *  $price 计算得到的价格
    *  $jifei_log_id 计费IP日志对应的ID
    *  $jiakuan_log_id  直接加款的日志ID
    **/
    private function user_shangji_jiakuan($price,$jifei_log_id,$jiakuan_log_id)
    {
        //下级也开启事务
        $M= M("user");
        $M->startTrans();
        $user_shangji=$this->user_shangji($this->user_pid);
        //查询不到上级直接返回
        if(empty($user_shangji)){
            return true;
        }
        $arr = array();
        foreach ($user_shangji as $key => $v) {
            $key++;
            $bili=C("USER_BAIFENBI_".$key); //获取配置的比例
            $price1 =($price * $bili) /100;
            $data['score'] = //
            $arr[] =$M->lock('true')->where("id=".$v)->setField(array(
                "balance"=>array('exp','balance+'.$price1),
                "xiaji"=>array('exp','xiaji+'.$price1), //下级总表+本次下级带来的分成
                "fans".$key =>array('exp','fans'.$key.'+'.$price1) //按粉丝等级总额字段加款
                ));
            $this->time_jifei_ip("xiaji",$price);
            //是否开启加款日志
            if(C("JIAKUAN_LOG_FANS")){
            $jiakuan_data=array(
                 "uid"=>$v,
                 'time'=>time()+$key+rand(3,10),
                 'price'=>$price1,
                 'type'=> 2,
                 'jifei_log_id' =>$jifei_log_id,
                 "jiakuan_log_id" =>$jiakuan_log_id,
                 'info' =>get_num_cn($key).'级上线返现加款.下线ID:'.$v."最顶层下线为:".$this->uid,
             );
            M("jiakuan_xiaji_log")->add($jiakuan_data);
            }
        }
        if(is_array_true($arr)){
            //事务提交
            $M->commit();
        }else{
            $M->rollback();//不成功，则回滚
        }

    }


    //添加计费总表
    //$type  计费字段 price 直接推广 shangji 上级返利
    //$price 要加的金额
    private function time_jifei_ip($type,$price)
    {
        //今日0点0分0秒
        $time = strtotime(date('Y-m-d',time()));
        $M=M("time_jifei_ip");
        //缓存1个小时
        if(!$M->lock('true')->where(array("time"=>$time))->find()){
         $data=array(
           "time"=>$time,
            $type=>$price
            );
          $M->add($data);
        }else{
         $s= $M->lock('true')->where(array("time"=>$time))->setInc($type,$price);

        }

    }


   //递归获取上级会员
   private function user_shangji($user_pid){
        $arr=array();
         if ($user_pid){
               if($user_pid==$this->user_pid){
                   $arr[]=$user_pid;
                }
                $user=M("user")->field("id,user_pid")->where("id=".$user_pid)->find();
                if($user['user_pid']){
                $arr[]=$user['user_pid'];
                $arr=array_merge($arr,self::user_shangji($user['user_pid']));
               }
             }
       return $arr;
    }



    //获取会员计费金额
    private function user_dianji()
    {
        $uid = $this->uid;
        $cid = $this->cid;
        $QUJU_DIANJI_PRICE= C("QUJU_DIANJI_PRICE"); //全局点击价格
        $_p=$QUJU_DIANJI_PRICE;
        //如果关闭全局点击费用开关!
        if(!C("QUJI_DIANJI")){
        $price=$this->user;
        if($price['price']==0){
           $price= M("cate")->field("price")->where("id=".$cid)->find();
        }
        $_p= $price['price']==0 ? $QUJU_DIANJI_PRICE : $price['price'];
        }
        $news_price=M("news")->field("price")->where("id=".$this->id)->find();
 
        if($news_price['price']> 0){
           $_p= $news_price['price'];
        }
        return $_p;
    }


   //匹配UId是不是为真，能不能查询到这个推广会员
    private function user_uid()
    {
       $uid = $this->uid;
       $user_uid=false;
       if($uid!==0){
         $user_uid=M("user")->where(array('id'=>$uid))->find();
         $this->user_pid=$user_uid['user_pid'];
       }
       if($user_uid){
          $user_uid=M("user")->where(array('id'=>$uid))->find(); ////////////////////////
          $this->user= $user_uid; //把查询到的会员信息付给$user.扣量的时候可以用到
          $this->lanjiinfo =  !$user_uid ? "会员状态已锁定!" : '';
       }else{
          $this->lanjiinfo="没加推广ID或者推广ID加密不正确!";
       }
       return $user_uid;
    }


    //匹配黑名单IP
    private function block_ip($ip)
    {
       $arrip=explode("\r\n", C("ARRIP"));
       if(is_array($arrip)){
           foreach ($arrip as $v)
           {
           if(ip_in_range(long2ip($ip),$v))
             {
               $this->lanjiinfo= "黑名单IP段".$v;
               return true;  //存在IP段库中
              }
           }
       }
       $M=M("block_ip");
       $block_ip=$M->where(array('ip'=>$ip))->count();
       if($block_ip){
          $M->where(array('ip'=>$ip))->setInc('num',1);
          $this->lanjiinfo= "数据库黑名单IP";
       }
       return $block_ip;
    }





    /*******************************************/

    //初始化防作弊
    public function Simple()
    {
        if($this->is_get_url()){
          if(!$this->is_uid())
          {
             $this->lanjiinfo="未加推广ID";
             return false;
          }
          //PC不计费
          if(!C("PC_JIFEI")){
              if(!$this->is_phome){
                 $this->lanjiinfo= "后台开启PC不计费配置!";
                 return false;
              }
          }
          //会员互相点击
          if(C("USER_DIANJI_JIFEI")){
               if($this->is_user_login_ip($ip))
                 {
                   $this->lanjiinfo= "会员互点或者会员登录IP!";
                   return false;
                  }
          }
          //地区验证
          if(C("USER_TONGYIDIQU_JIFEI"))
          {

          }
          //验证是否朋友圈
          if(C("PENGYOUQUAN_JIFEI"))
          {
             if(!$this->is_pengyouquan())
             {
                $this->lanjiinfo= "好友分享或者微信群点击!";
                return false;
             }
          }
          //高级防作弊模式
          if(C("GAOJI_LANJIE"))
           {
              if(!$this->gaoji_lanjie())
              {
                 return false;
              }
           }
           return true;
        }
        return false;
    }

    /*****初始验证*******/
    //高级防作弊
    private function gaoji_lanjie()
    {
        $app_weixin = strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger/');
        $app_qq = strpos($_SERVER['HTTP_USER_AGENT'], 'QQ/');
        if ($app_weixin!== false || $app_qq!==false ) {
            return true;
        }
         $this->lanjiinfo="未通过高级防作弊模块扫描!";
         return false;
    }


    //判断域名是否正确
    private function is_yumi()
    {
        $url=$this->yumi_url;
        $yumi = $_SERVER['HTTP_HOST'];
        if($yumi==$url){
            return true;
        }else{
            $this->lanjiinfo= "访问域名不正确!";
            return false;
        }
    }


    //获取来路
    private function is_get_url()
    {
        $get_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
        $site_url = C("SITE_URL");
        if(strpos($get_url,$site_url)){
           $this->lanjiinfo= "会员内部登陆!";
           return false;
        }else{
           return true; //如果不等于初始判断通过
        }
    }


    //匹配是不是微信或者QQapp打开
    private function is_weixin_qq()
    {
        $useragent=$this->useragent->useragent;
        $app_weixin = strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger/');
        $app_qq = strpos($_SERVER['HTTP_USER_AGENT'], 'QQ/');
        if ($app_weixin!== false || $app_qq!==false ) {
            return true;
        }
         $this->lanjiinfo="未通过高级防作弊模块扫描!";
        return false;
    }


    //判断是否来自朋友圈只能简单防止作弊
    private function is_pengyouquan()
    {
        $from= I('get.from');
        if(isset($from)){
            if($from=='timeline'){
                return true;
            }
        }
        return false;
    }


    //匹配IP是不是会员的登陆的IP
    private function is_user_login_ip()
    {
       $ip=iplong($this->ip);
       $login_ip=M("user")->where(array("login_ip"=>$ip))->find();
       return $login_ip;
    }


    private function is_uid()
    {

        $uid=I('get.uid');
        if(empty($uid)){
            return false;
        }else{
            return true;
        }
    }





  }
?>